<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
    >
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入活动名称" />
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="活动开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              placeholder="请选择时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="活动结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="请选择时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="打卡规则" prop="checkInRule">
        <div class="punch-rule-container">
          <el-select 
            v-model="formData.checkInRule" 
            placeholder="请选择打卡规则" 
            @change="handleCheckInRuleChange"
            class="punch-rule-select"
          >
            <el-option label="持续打卡" value="continuous" />
            <el-option label="非持续打卡" value="non-continuous" />
            <el-option label="无需打卡" value="no-checkin" />
          </el-select>
          <div v-if="formData.checkInRule === 'continuous' || formData.checkInRule === 'non-continuous'" class="punch-days-container">
            <el-input-number
              v-model="formData.checkInDays"
              :min="1"
              placeholder="天数"
              class="punch-days-input"
            />
            <span class="punch-days-text">天</span>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="每日打卡时间" prop="dailyCheckInTimes" v-if="formData.checkInRule !== 'no-checkin'">
        <template #label>
          <span>每日打卡时间</span>
          <el-tooltip content="可选填，如不填写则默认为全天（00:00-23:59）" placement="top">
            <Icon icon="ep:question-filled" class="ml-1 text-gray-400" />
          </el-tooltip>
        </template>
        <div class="time-range-container">
          <div v-for="(timeRange, index) in formData.dailyCheckInTimes" :key="index" class="time-range-item">
            <span class="time-range-label">时间段{{ index + 1 }}：</span>
            <el-time-picker
              v-model="timeRange.startTime"
              placeholder="开始时间"
              format="HH:mm"
              value-format="HH:mm"
              @change="validateTimeRanges"
            />
            <span class="time-separator">-</span>
            <el-time-picker
              v-model="timeRange.endTime"
              placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              :disabled-hours="() => getDisabledEndHours(timeRange)"
              :disabled-minutes="(hour) => getDisabledEndMinutes(timeRange, hour)"
              @change="validateTimeRanges"
            />
            <el-button
              v-if="formData.dailyCheckInTimes.length > 1"
              type="danger"
              link
              @click="removeTimeRange(index)"
              class="delete-btn"
            >
              <Icon icon="ep:delete" />
            </el-button>
          </div>
          <div class="add-time-button">
            <el-button 
              type="primary" 
              plain 
              @click="addTimeRange"
              :disabled="formData.dailyCheckInTimes.length >= 5"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 
              添加时间段 ({{ formData.dailyCheckInTimes.length }}/5)
            </el-button>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="活动期后上传凭证" prop="uploadProofAfter">
        <el-radio-group v-model="formData.uploadProofAfter" @change="handleUploadProofChange">
          <el-radio :value="true" class="radio-item">是</el-radio>
          <el-radio 
            :value="false" 
            :disabled="formData.checkInRule === 'no-checkin'"
          >
            否
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- <el-form-item label="流程是否需要审核" prop="needAudit">
        <el-radio-group v-model="formData.needAudit">
          <el-radio :value="true" class="radio-item">是</el-radio>
          <el-radio :value="false">否</el-radio>
        </el-radio-group>
      </el-form-item> -->

      <el-form-item label="活动细则" prop="rules">
        <el-input
          v-model="formData.rules"
          type="textarea"
          :rows="4"
          placeholder="请输入活动细则"
        />
      </el-form-item>

      <el-form-item label="选择商品" prop="selectedProducts">
        <div class="product-selection">
          <el-button type="primary" @click="openProductSelect">选择商品</el-button>
          
          <!-- 已选商品展示 -->
          <div v-if="selectedProducts.length > 0" class="selected-products">
            <div class="selected-products-header">
              <span>已选商品 ({{ selectedProducts.length }})</span>
              <el-button type="danger" link @click="clearAllProducts">清空全部</el-button>
            </div>
            <el-table :data="selectedProducts" stripe>
              <el-table-column label="商品编号" prop="id" width="100" />
              <el-table-column label="商品图" width="100">
                <template #default="scope">
                  <el-image
                    :src="scope.row.picUrl || ''"
                    style="width: 60px; height: 60px"
                    :preview-src-list="scope.row.picUrl ? [scope.row.picUrl] : []"
                    preview-teleported
                    fit="cover"
                  />
                </template>
              </el-table-column>
              <el-table-column label="商品名称" prop="name" min-width="200" />
              <el-table-column label="商品分类" prop="categoryName" width="120">
                <template #default="scope">
                  <span>{{ scope.row.categoryName || '未分类' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    @click="removeProduct(scope.$index)"
                  >
                    <Icon icon="ep:delete" />
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 未选择商品提示 -->
          <div v-else class="no-products">
            <Icon icon="ep:box" class="no-products-icon" />
            <span>暂未选择商品</span>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">确定</el-button>
    </template>
  </Dialog>

  <!-- 本地生活商品选择对话框 -->
  <LocalLifeSpuSelect ref="spuTableSelectRef" :multiple="true" @change="handleProductSelected" />
</template>

<script setup lang="ts">
/** 退款活动表单 */
defineOptions({ name: 'RefundActivityForm' })

import LocalLifeSpuSelect from '@/views/mall/product/spu/components/LocalLifeSpuSelect.vue'
import * as LocalLifeSpuApi from '@/api/localLife/spu'
import * as LocalLifeCategoryApi from '@/api/localLife/category'
import * as RefundActivityApi from '@/api/mall/promotion/refund/refundActivity'
import type { RefundActivityCreateReqVO, RefundActivityUpdateReqVO } from '@/api/mall/promotion/refund/refundActivity'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<{
  id: number | undefined
  name: string
  startTime: string
  endTime: string
  checkInRule: string
  checkInDays: number
  dailyCheckInTimes: Array<{ startTime: string; endTime: string }>
  uploadProofAfter: boolean
  needAudit: boolean
  rules: string
  selectedProducts: LocalLifeSpuApi.Spu[]
}>({
  id: undefined,
  name: '',
  startTime: '',
  endTime: '',
  checkInRule: '',
  checkInDays: 1,
  dailyCheckInTimes: [{ startTime: '', endTime: '' }],
  uploadProofAfter: false,
  needAudit: false,
  rules: '',
  selectedProducts: []
})
const formRules = reactive({
  name: [{ required: true, message: '活动名称不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '活动开始时间不能为空', trigger: 'change' }],
  endTime: [{ required: true, message: '活动结束时间不能为空', trigger: 'change' }],
  checkInRule: [{ required: true, message: '打卡规则不能为空', trigger: 'change' }],
  dailyCheckInTimes: [
    {
      validator: (rule: any, value: Array<{ startTime: string; endTime: string }>, callback: Function) => {
        // 检查是否为必需的打卡规则
        if (formData.value.checkInRule === 'no-checkin') {
          callback()
          return
        }
        
        // 如果没有时间段或者时间段为空，允许通过（将在提交时设置为默认全天）
        if (!value || value.length === 0) {
          callback()
          return
        }
        
        // 过滤掉空的时间段
        const filledTimeRanges = value.filter(timeRange => 
          timeRange.startTime && timeRange.endTime
        )
        
        // 如果所有时间段都是空的，允许通过
        if (filledTimeRanges.length === 0) {
          callback()
          return
        }
        
        // 检查已填写时间段的有效性
        for (let i = 0; i < filledTimeRanges.length; i++) {
          const timeRange = filledTimeRanges[i]
          
          // 检查开始时间是否在结束时间之前
          if (timeRange.startTime >= timeRange.endTime) {
            const originalIndex = value.findIndex(t => t === timeRange) + 1
            callback(new Error(`第${originalIndex}个时间段：开始时间必须在结束时间之前`))
            return
          }
        }
        
        // 检查时间段是否重叠
        const sortedRanges = [...filledTimeRanges].sort((a, b) => a.startTime.localeCompare(b.startTime))
        for (let i = 0; i < sortedRanges.length - 1; i++) {
          const current = sortedRanges[i]
          const next = sortedRanges[i + 1]
          
          if (current.endTime > next.startTime) {
            callback(new Error('时间段之间不能存在重叠，请检查时间设置'))
            return
          }
        }
        
        callback()
      },
      trigger: 'change'
    }
  ],
  uploadProofAfter: [
    {
      validator: (rule: any, value: boolean, callback: Function) => {
        if (formData.value.checkInRule === 'no-checkin' && !value) {
          callback(new Error('选择无需打卡时，活动期后上传凭证必须为是'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  rules: [{ required: true, message: '活动细则不能为空', trigger: 'blur' }],
  selectedProducts: [{ required: true, message: '请选择商品', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

// 商品选择相关
const selectedProducts = ref<LocalLifeSpuApi.Spu[]>([])
const spuTableSelectRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await RefundActivityApi.getRefundActivity(id)
      formData.value = {
        id: data.id,
        name: data.name,
        startTime: data.startTime ? formatDateTimeLocal(data.startTime) : '',
        endTime: data.endTime ? formatDateTimeLocal(data.endTime) : '',
        checkInRule: getPunchCardRuleKey(data.punchCardRule),
        checkInDays: data.punchCardDays || 1,
        dailyCheckInTimes: parseDailyCheckInTimes(data.everydayPunchPeriods),
        uploadProofAfter: data.activityUploadProof,
        needAudit: data.proofCheck,
        rules: data.activityRule || '',
        selectedProducts: []
      }
      
      // 根据products中的spuId查询商品详情并转换为selectedProducts格式
      if (data.products && data.products.length > 0) {
        try {
          const spuIds = data.products.map(p => p.spuId)
          const productList = await LocalLifeSpuApi.getSpuDetailList(spuIds)
          
          if (productList && productList.length > 0) {
            // 获取分类信息并添加到商品数据中
            const productsWithCategory = await addCategoryNames(productList)
            selectedProducts.value = productsWithCategory
            formData.value.selectedProducts = selectedProducts.value
          } else {
            selectedProducts.value = []
            formData.value.selectedProducts = []
          }
        } catch (error) {
          console.error('查询商品详情失败:', error)
          selectedProducts.value = []
          formData.value.selectedProducts = []
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  // 校验商品选择
  if (selectedProducts.value.length === 0) {
    message.error('请选择商品')
    return
  }
  
  // 提交请求
  formLoading.value = true
  try {
    // 处理每日打卡时间
    let dailyCheckInPeriods = undefined
    if (formData.value.checkInRule !== 'no-checkin') {
      // 过滤掉空的时间段
      const filledTimeRanges = formData.value.dailyCheckInTimes.filter(t => 
        t.startTime && t.endTime
      )
      
      if (filledTimeRanges.length > 0) {
        // 如果用户填写了时间段，使用用户填写的
        dailyCheckInPeriods = JSON.stringify(
          filledTimeRanges.map(t => ({ start: t.startTime, end: t.endTime }))
        )
      } else {
        // 如果用户没有填写时间段，默认为全天
        dailyCheckInPeriods = JSON.stringify([
          { start: '00:00', end: '23:59' }
        ])
      }
    }

    // 构造提交数据
    const submitData = {
      name: formData.value.name,
      startTime: new Date(formData.value.startTime).getTime(),
      endTime: new Date(formData.value.endTime).getTime(),
      punchCardRule: getPunchCardRuleValue(formData.value.checkInRule),
      punchCardDays: (formData.value.checkInRule === 'continuous' || formData.value.checkInRule === 'non-continuous') 
        ? formData.value.checkInDays : undefined,
      everydayPunchPeriods: dailyCheckInPeriods,
      activityUploadProof: formData.value.uploadProofAfter,
      proofCheck: formData.value.needAudit,
      notifyCopy: undefined, // 表单中暂未包含此字段
      activityRule: formData.value.rules,
      products: selectedProducts.value.map(p => ({ spuId: p.id })) // 只发送spuId
    }
    
    if (formType.value === 'create') {
      await RefundActivityApi.createRefundActivity(submitData as RefundActivityCreateReqVO)
      message.success(t('common.createSuccess'))
    } else {
      await RefundActivityApi.updateRefundActivity({
        id: formData.value.id!,
        ...submitData
      } as RefundActivityUpdateReqVO)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 获取打卡规则对应的数值 */
const getPunchCardRuleValue = (rule: string): number => {
  switch (rule) {
    case 'continuous':
      return 1
    case 'non-continuous':
      return 2
    case 'no-checkin':
      return 3
    default:
      return 1
  }
}

/** 获取打卡规则对应的字符串key */
const getPunchCardRuleKey = (rule: number): string => {
  switch (rule) {
    case 1:
      return 'continuous'
    case 2:
      return 'non-continuous'
    case 3:
      return 'no-checkin'
    default:
      return 'continuous'
  }
}

/** 解析每日打卡时间 */
const parseDailyCheckInTimes = (periodsStr?: string) => {
  if (!periodsStr) {
    return [{ startTime: '', endTime: '' }]
  }
  try {
    const periods = JSON.parse(periodsStr)
    return periods.map((p: any) => ({ startTime: p.start, endTime: p.end }))
  } catch {
    return [{ startTime: '', endTime: '' }]
  }
}

/** 格式化日期时间为本地时间字符串（用于表单显示） */
const formatDateTimeLocal = (dateTime: string | number) => {
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    startTime: '',
    endTime: '',
    checkInRule: '',
    checkInDays: 1,
    dailyCheckInTimes: [{ startTime: '', endTime: '' }],
    uploadProofAfter: false,
    needAudit: false,
    rules: '',
    selectedProducts: []
  }
  selectedProducts.value = []
  formRef.value?.resetFields()
}

/** 打卡规则变更处理 */
const handleCheckInRuleChange = (value: string) => {
  if (value === 'no-checkin') {
    // 无需打卡时，活动期后上传凭证必须为true
    formData.value.uploadProofAfter = true
    message.info('选择无需打卡时，必须开启活动期后上传凭证')
  }
  // 触发表单验证
  nextTick(() => {
    formRef.value?.validateField('uploadProofAfter')
    formRef.value?.validateField('dailyCheckInTimes')
  })
}

/** 上传凭证变更处理 */
const handleUploadProofChange = (value: boolean) => {
  if (!value && formData.value.checkInRule === 'no-checkin') {
    // 如果选择了无需打卡，则不能关闭活动期后上传凭证
    formData.value.uploadProofAfter = true
    message.warning('选择无需打卡时，活动期后上传凭证必须开启')
  }
}

/** 添加时间段 */
const addTimeRange = () => {
  if (formData.value.dailyCheckInTimes.length >= 5) {
    message.warning('最多只能添加5个时间段')
    return
  }
  formData.value.dailyCheckInTimes.push({ startTime: '', endTime: '' })
}

/** 删除时间段 */
const removeTimeRange = (index: number) => {
  formData.value.dailyCheckInTimes.splice(index, 1)
  // 删除后重新验证
  nextTick(() => {
    validateTimeRanges()
  })
}

/** 验证时间段 */
const validateTimeRanges = () => {
  nextTick(() => {
    formRef.value?.validateField('dailyCheckInTimes')
  })
}

/** 获取结束时间禁用的小时 */
const getDisabledEndHours = (timeRange: { startTime: string; endTime: string }) => {
  const disabledHours: number[] = []
  
  if (timeRange.startTime) {
    const startHour = parseInt(timeRange.startTime.split(':')[0])
    // 禁用小于开始时间小时的所有小时
    for (let i = 0; i < startHour; i++) {
      disabledHours.push(i)
    }
  }
  
  return disabledHours
}

/** 获取结束时间禁用的分钟 */
const getDisabledEndMinutes = (timeRange: { startTime: string; endTime: string }, hour: number) => {
  const disabledMinutes: number[] = []
  
  if (timeRange.startTime) {
    const [startHour, startMinute] = timeRange.startTime.split(':').map(Number)
    
    // 如果当前选择的小时等于开始时间的小时，则禁用小于等于开始时间分钟的所有分钟
    if (hour === startHour) {
      for (let i = 0; i <= startMinute; i++) {
        disabledMinutes.push(i)
      }
    }
  }
  
  return disabledMinutes
}

/** 打开商品选择对话框 */
const openProductSelect = () => {
  spuTableSelectRef.value.open(selectedProducts.value)
}

/** 处理商品选择 */
const handleProductSelected = async (products: LocalLifeSpuApi.Spu[]) => {
  // 为选择的商品添加分类名称
  const productsWithCategory = await addCategoryNames(products)
  selectedProducts.value = productsWithCategory
  formData.value.selectedProducts = selectedProducts.value
  // 手动触发表单验证
  formRef.value?.validateField('selectedProducts')
}

/** 移除单个商品 */
const removeProduct = (index: number) => {
  selectedProducts.value.splice(index, 1)
  formData.value.selectedProducts = selectedProducts.value
  // 手动触发表单验证
  formRef.value?.validateField('selectedProducts')
}

/** 清空所有商品 */
const clearAllProducts = () => {
  selectedProducts.value = []
  formData.value.selectedProducts = []
  // 手动触发表单验证
  formRef.value?.validateField('selectedProducts')
}

/** 添加分类名称到商品数据中 */
const addCategoryNames = async (products: LocalLifeSpuApi.Spu[]): Promise<LocalLifeSpuApi.Spu[]> => {
  try {
    // 获取所有分类ID
    const categoryIds = [...new Set(products.map(p => p.categoryId).filter(id => id))]
    
    if (categoryIds.length === 0) {
      return products.map(p => ({ ...p, categoryName: '未分类' }))
    }
    
    // 获取分类列表
    const categoryList = await LocalLifeCategoryApi.getCategoryList({})
    const categoryMap = new Map()
    
    if (categoryList && categoryList.length > 0) {
      categoryList.forEach(category => {
        categoryMap.set(category.id, category.name)
      })
    }
    
    // 为商品添加分类名称
    return products.map(product => ({
      ...product,
      categoryName: categoryMap.get(product.categoryId) || '未分类'
    }))
  } catch (error) {
    console.error('获取分类信息失败:', error)
    return products.map(p => ({ ...p, categoryName: '未分类' }))
  }
}
</script>

<style scoped>
.time-range-container {
  width: 100%;
}

.time-range-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.time-range-label {
  font-weight: 500;
  color: #495057;
  min-width: 80px;
  margin-right: 12px;
}

.time-separator {
  margin: 0 12px;
  color: #6c757d;
  font-weight: 500;
}

.delete-btn {
  margin-left: 12px;
  color: #dc3545;
}

.delete-btn:hover {
  color: #c82333;
}

.add-time-button {
  text-align: right;
  margin-top: 16px;
}

.radio-item {
  margin-right: 30px;
}

.product-selection {
  width: 100%;
}

.selected-products {
  margin-top: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  background-color: #fafafa;
}

.selected-products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: 500;
  color: #303133;
}

.no-products {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #909399;
  background-color: #fafafa;
  border: 1px dashed #e4e7ed;
  border-radius: 6px;
  margin-top: 15px;
}

.no-products-icon {
  font-size: 48px;
  margin-bottom: 10px;
  color: #c0c4cc;
}

.price-text {
  color: #f56c6c;
  font-weight: 500;
}



/* 打卡规则样式 */
.punch-rule-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.punch-rule-select {
  width: 200px;
}

.punch-days-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.punch-days-input {
  width: 100px;
}

.punch-days-text {
  color: #606266;
  font-size: 14px;
}


</style> 
